<template>
  <div class="patient-tcm-records">
    <!-- 头部区域 -->
    <div class="panel-header">
      <h2><el-icon><MagicStick /></el-icon> 我的中医辨证记录</h2>
      <div class="header-actions">
        <el-select
            v-model="selectedSymptom"
            placeholder="选择症状"
            clearable
            @change="fetchRecords"
            style="width: 180px; margin-right: 15px;"
        >
          <el-option
              v-for="symptom in symptomOptions"
              :key="symptom.value"
              :label="symptom.label"
              :value="symptom.value"
          />
        </el-select>
        <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :disabled-date="disabledFutureDates"
            @change="fetchRecords"
            style="margin-right: 15px;"
        />
        <el-button type="primary" @click="refreshRecords">
          <el-icon><Refresh /></el-icon> 刷新记录
        </el-button>
      </div>
    </div>

    <!-- 记录列表 -->
    <div class="records-container">
      <el-timeline v-if="filteredRecords.length > 0">
        <el-timeline-item
            v-for="(record, index) in filteredRecords"
            :key="index"
            :timestamp="formatDate(record.date)"
            placement="top"
        >
          <el-card class="record-card" shadow="hover" @click="viewRecord(record)">
            <div class="card-header">
              <h3>{{ record?.syndromeType || '未填写证型' }}</h3>
              <el-tag type="info">
                {{ formatDate(record.date) }}
              </el-tag>
            </div>
            <div class="card-content">
              <p class="complaint">{{ record?.chiefComplaint || '无主诉' }}</p>
              <div class="diagnosis-info">
                <span><strong>舌象：</strong>{{ record?.tongue || '未记录' }}</span>
                <span><strong>脉象：</strong>{{ record?.pulse || '未记录' }}</span>
              </div>
              <div class="treatment-summary">
                <span><strong>治法：</strong>{{ record?.treatment?.method || '未记录' }}</span>
                <span><strong>药味数：</strong>{{ record?.treatment?.herbs?.length || 0 }}味</span>
              </div>
            </div>
          </el-card>
        </el-timeline-item>
      </el-timeline>

      <el-empty v-else description="暂无中医辨证记录" />
    </div>

    <!-- 记录详情对话框 -->
    <el-dialog
        v-model="detailDialogVisible"
        :title="'中医辨证详情 - ' + (currentRecord?.syndromeType || '未填写证型')"
        width="800px"
    >
      <div v-if="currentRecord" class="record-detail">
        <div class="detail-header">
          <div class="detail-meta">
            <span class="date">{{ formatDate(currentRecord.date) }}</span>
          </div>
        </div>

        <div class="detail-section">
          <h4>主诉</h4>
          <p>{{ currentRecord.chiefComplaint || '无主诉' }}</p>
        </div>

        <div class="detail-section">
          <h4>四诊信息</h4>
          <div class="four-diagnosis">
            <div>
              <h5>望诊</h5>
              <p>{{ currentRecord.inspection || '未记录' }}</p>
            </div>
            <div>
              <h5>闻诊</h5>
              <p>{{ currentRecord.listening || '未记录' }}</p>
            </div>
            <div>
              <h5>问诊</h5>
              <p>{{ currentRecord.inquiry || '未记录' }}</p>
            </div>
            <div>
              <h5>切诊</h5>
              <p>{{ currentRecord.palpation || '未记录' }}</p>
            </div>
          </div>
        </div>

        <div class="detail-section">
          <h4>舌象</h4>
          <p>{{ currentRecord.tongue || '未记录' }}</p>
        </div>

        <div class="detail-section">
          <h4>脉象</h4>
          <p>{{ currentRecord.pulse || '未记录' }}</p>
        </div>

        <div class="detail-section">
          <h4>辨证结论</h4>
          <el-tag type="success" size="large">{{ currentRecord.syndromeType || '未填写证型' }}</el-tag>
        </div>

        <div class="detail-section">
          <h4>治法</h4>
          <p>{{ currentRecord.treatment?.method || '未记录' }}</p>
        </div>

        <div class="detail-section">
          <h4>方药组成</h4>
          <div class="herbs-list">
            <template v-if="currentRecord.treatment?.herbs?.length > 0">
              <el-tag
                  v-for="(herb, index) in currentRecord.treatment.herbs"
                  :key="index"
                  type="info"
                  size="large"
              >
                {{ herb.name }} {{ herb.dosage }}{{ herb.unit }}
              </el-tag>
            </template>
            <span v-else>未开具方药</span>
          </div>
        </div>

        <div class="detail-section" v-if="currentRecord.treatment?.advice">
          <h4>医嘱</h4>
          <p>{{ currentRecord.treatment.advice }}</p>
        </div>
      </div>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="printRecord">打印记录</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, computed, onMounted} from 'vue'
import {ElMessage} from 'element-plus'
import {MagicStick, Refresh} from '@element-plus/icons-vue'
import dayjs from 'dayjs'

dayjs.locale('zh-cn')
// 表格数据
const records = ref([])
const loading = ref(false)
const dateRange = ref([])
const selectedSymptom = ref('')
const detailDialogVisible = ref(false)
const currentRecord = ref({
  syndromeType: '',
  date: new Date(),
  chiefComplaint: '',
  inspection: '',
  listening: '',
  inquiry: '',
  palpation: '',
  tongue: '',
  pulse: '',
  treatment: {
    method: '',
    herbs: [],
    advice: ''
  }
})

// 症状选项
const symptomOptions = ref([
  {value: 'headache', label: '头痛'},
  {value: 'stomachache', label: '胃痛'},
  {value: 'dizziness', label: '头晕'},
  {value: 'insomnia', label: '失眠'},
  {value: 'cough', label: '咳嗽'}
])

// 模拟获取记录数据
const fetchRecords = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))

    records.value = [
      {
        id: 1,
        date: '2023-05-15',
        chiefComplaint: '反复头痛3个月，加重1周',
        syndromeType: '肝阳上亢证',
        inspection: '面色红赤',
        listening: '言语急促',
        inquiry: '头痛以两侧为主，伴头晕目眩',
        palpation: '头部触诊无异常',
        tongue: '舌红少苔',
        pulse: '弦数',
        treatment: {
          method: '平肝潜阳',
          herbs: [
            {name: '天麻', dosage: 10, unit: 'g'},
            {name: '钩藤', dosage: 12, unit: 'g'},
            {name: '石决明', dosage: 15, unit: 'g'},
            {name: '栀子', dosage: 10, unit: 'g'},
            {name: '黄芩', dosage: 10, unit: 'g'}
          ],
          advice: '避免熬夜，保持情绪稳定，忌食辛辣刺激食物'
        }
      },
      {
        id: 2,
        date: '2023-04-10',
        chiefComplaint: '胃脘胀痛1周，嗳气频繁',
        syndromeType: '肝气犯胃证',
        inspection: '面色青黄',
        listening: '嗳气声频',
        inquiry: '胃痛与情绪波动相关',
        palpation: '上腹轻压痛',
        tongue: '舌淡红苔薄白',
        pulse: '弦',
        treatment: {
          method: '疏肝和胃',
          herbs: [
            {name: '柴胡', dosage: 10, unit: 'g'},
            {name: '白芍', dosage: 12, unit: 'g'},
            {name: '陈皮', dosage: 6, unit: 'g'},
            {name: '香附', dosage: 10, unit: 'g'}
          ],
          advice: '少食多餐，忌食生冷，保持心情舒畅'
        }
      }
    ]

    // 模拟症状筛选
    if (selectedSymptom.value) {
      records.value = records.value.filter(record =>
          record.chiefComplaint.includes(symptomOptions.value.find(s => s.value === selectedSymptom.value)?.label || '')
      )
    }
  } catch (error) {
    ElMessage.error('获取记录失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 过滤后的记录
const filteredRecords = computed(() => {
  let result = records.value

  // 按日期过滤
  if (dateRange.value && dateRange.value.length === 2) {
    const [start, end] = dateRange.value
    result = result.filter(record => {
      const recordDate = new Date(record.date)
      return recordDate >= start && recordDate <= end
    })
  }

  return result
})

// 查看记录详情
const viewRecord = (record) => {
  currentRecord.value = {
    ...{
      syndromeType: '',
      date: new Date(),
      chiefComplaint: '',
      inspection: '',
      listening: '',
      inquiry: '',
      palpation: '',
      tongue: '',
      pulse: '',
      treatment: {
        method: '',
        herbs: [],
        advice: ''
      }
    },
    ...record
  }
  detailDialogVisible.value = true
}

// 刷新记录
const refreshRecords = () => {
  selectedSymptom.value = ''
  dateRange.value = []
  fetchRecords()
}

// 打印记录
const printRecord = () => {
  window.print()
}

// 格式化日期
const formatDate = (date) => {
  return dayjs(date).format('YYYY年-MM月-DD日')
}

const formatDateWithWeekday = (date) => {
  return dayjs(date).format('YYYY年MM月DD日 dddd')
}

// 禁用未来日期
const disabledFutureDates = (time) => {
  return time.getTime() > Date.now()
}

onMounted(() => {
  fetchRecords()
})
</script>

<style scoped>
.patient-tcm-records {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100%;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.panel-header h2 {
  margin: 0;
  display: flex;
  align-items: center;
  font-size: 18px;
}

.panel-header .el-icon {
  margin-right: 8px;
}

.header-actions {
  display: flex;
  align-items: center;
}

.records-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.record-card {
  cursor: pointer;
  transition: transform 0.3s;
  margin-bottom: 10px;
}

.record-card:hover {
  transform: translateY(-3px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.card-header h3 {
  margin: 0;
  color: #333;
}

.card-content {
  color: #666;
}

.complaint {
  font-weight: 500;
  margin-bottom: 8px;
}

.diagnosis-info, .treatment-summary {
  display: flex;
  gap: 15px;
  margin: 8px 0;
  font-size: 14px;
}

.record-detail {
  padding: 10px;
}

.detail-header {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.detail-meta {
  display: flex;
  align-items: center;
  gap: 15px;
  color: #666;
}

.date {
  font-size: 14px;
}

.detail-section {
  margin-bottom: 20px;
}

.detail-section h4 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 16px;
}

.detail-section p {
  margin: 0;
  color: #666;
  line-height: 1.6;
}

.four-diagnosis {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
}

.four-diagnosis h5 {
  margin: 0 0 5px 0;
  font-size: 14px;
  color: #333;
}

.herbs-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

@media print {
  .patient-tcm-records > *:not(.record-detail) {
    display: none;
  }

  .record-detail {
    padding: 0;
  }

  .el-dialog {
    position: static;
    margin: 0;
    box-shadow: none;
  }

  .el-dialog__header, .el-dialog__footer {
    display: none;
  }
}

@media (max-width: 768px) {
  .panel-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .header-actions {
    width: 100%;
    flex-direction: column;
    align-items: flex-start;
  }

  .four-diagnosis {
    grid-template-columns: 1fr;
  }

  .diagnosis-info, .treatment-summary {
    flex-direction: column;
    gap: 5px;
  }
}
</style>
